package com.zh.mq.tx.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.constants.Constants;
import com.zh.pojo.bo.PayOrderBo;
import com.zh.pojo.domain.Order;
import com.zh.service.IOrderService;
import com.zh.utils.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

// MQ事务监听器

@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup = Constants.MQ.TX_GROUP_PAY_ORDER)
public class MQSendListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IOrderService orderService;


    /**
     * @param message 构建消息
     * @param args 扩展参数
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object args) {
        try {
            // 扩展参数就是自己 执行本地事务操作的 对象
            Order order = (Order) args;
            orderService.updateById(order);
            // 本地事务保存成功则 发送提交命令
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e) {
            e.printStackTrace();
            // 发送消息失败则 提交回滚命令
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    /**
     * 回查机制，  根据订单号 查询数据库中订单状态是否修改成功，
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        PayOrderBo payOrderBo = (PayOrderBo) message.getPayload();
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, payOrderBo.getOrderNo()));
        AssertUtil.isNotNull(order, "订单不存在");
        // 订单状态是否修改成功
        if (order.getStatus().equals(Constants.Order.ORDER_STATUS_NOT_PAY)) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
